package com.ggh.handler;
import java.util.*;

import com.ggh.entity.RoomBeanP;
import com.ggh.entity.TypeBean;
import com.ggh.entity.User;
import com.ggh.entity.UserBean;
import com.ggh.service.UserRecordService;
import com.ggh.service.UserService;
import com.ggh.service.impl.UserRecordServiceImpl;
import com.ggh.service.impl.UserServiceImpl;
import com.ggh.util.ApplicationContextProvider;
import com.ggh.util.JsonUtils;
import com.ggh.websocket.PK_WebSocket_P;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.stream.Collectors;

/**
 * @author jj
 * @date 2019/10/9 11:38
 */
public class RoomProcess {
    /**
     * json转换类
     */
    Gson gson = JsonUtils.get();
    /**
     * 用户逻辑
     */
    private UserService userService=ApplicationContextProvider.getBean(UserServiceImpl.class);
    /**
     * 战绩添加
     */
    private UserRecordService userRecordService=ApplicationContextProvider.getBean(UserRecordServiceImpl.class);;
    /**
     * 游戏逻辑判断输赢
     */
    private BeginToJudgePKPSiRen pkx=new BeginToJudgePKPSiRen();
    /**
     * 工具类
     */
    private UserOperationP oper=new UserOperationP();


    /**
     * @description :抢庄倒计时
     * @param room
     * @param timer
     * @return: int
     * @date : 2019/10/9 11:45
     * @author : jj
     * @throws
     */
    public int qzdjs(RoomBeanP room,int timer){
        /**
         * 房间人数
         */
        int a = 0;
        /**
         *  抢庄人数
         */
        int b = 0;
        /**
         * 循环判断该抢庄人数
         */
        for (int i = 0; i < room.getUser_positions().length; i++) {
            if (room.getUser_positions()[i] == -1) {
                continue;
            }
            UserBean u = room.getUserBean(room.getUser_positions()[i]);
            if (u.getBanker() != 1) {
                continue;
            }
            a++;
            if (u.getUpbanker() != 0) {
                b++;
            }
        }
        System.out.println("在座a：" + a + ",选择b：" + b);
        /**
         * 房间内所有人已对抢庄做出选择，提前结束抢庄
         */
        if (a == b) {
            room.setTime(0);
            timer = 0;
            System.out.println("房间时间" + room.getTime());
        }
        return timer;
    }
    /**
     * @description :抢庄倒计时结束
     * 开始游戏
     * @param room
     * @return: void
     * @date : 2019/10/9 11:54
     * @author : jj
     * @throws
     */
    public void qzdjsjs(RoomBeanP room,Map<String, Object> map){
        if (room.getGame_number() == 0 || room.getGame_number() == 1) {
            room.setGame_number(1);
            //获取user信息
            for (UserBean uz : room.getGame_userlist()) {
                //判断是否是机器人
                if (uz.getIsAi()==1){
                    continue;
                }
                /*房费*/
                uz.setMoney(uz.getMoney() - (room.getMoney()));
                User ur = userService.getById(uz.getUserid());
                ur.setMoney(uz.getMoney());
                userService.updateById(ur);
            }
            map.put("type", TypeBean.SiRenGameInciDent);
            map.put("messages", gson.toJson(room));
            sendMessageAll(map, room);
        }
        room.setState(3);
    }
    /**
     * @description :开始定庄
     * @param room
     * @param timer
     * @param map
     * @return: int
     * @date : 2019/10/9 11:58
     * @author : jj
     * @throws
     */
    public int ksdz(RoomBeanP room, int timer, Map<String, Object> map){
        System.out.println("抢庄倒计时：" + timer);
        // 执行定庄方法
        oper.fixedBanker(room);
        /* 修改时间 */
        room.setTime(room.getTime03());
        timer = room.getTime();
        map.put("type", TypeBean.SiRenGameInciDent);
        map.put("messages", gson.toJson(room));
        sendMessageAll(map, room);
        // 修改状态下注倒计时
        room.setState(4);
        return timer;
    }
    /**
     * @description :开始下注
     * @param room
     * @param timer
     * @return: int
     * @date : 2019/10/9 16:11
     * @author : jj
     * @throws
     */
    public int ksxz(RoomBeanP room, int timer){
        // 房间人数
        int a = 0;
        // 下注人数
        int b = 0;
        // 循环判断该抢庄人数
        for (int i = 0; i < room.getUser_positions().length; i++) {
            if (room.getUser_positions()[i] == -1) {
                continue;
            }
            UserBean u = room.getUserBean(room.getUser_positions()[i]);
            /*庄家不参与*/
            if (u.getBanker()!=2){
                a++;
            }
            if (1 == u.getPower_type()) {
                b++;
            }
        }
        /*添加筛子*/
        if (room.getSaizhi()==null) {
            int num1 = (int) (Math.random() * 6);
            int num2 = (int) (Math.random() * 6);
            int[] saizhi = {num1, num2};
            room.setSaizhi(saizhi);
        }
        System.out.println("在座a：" + a + ",选择b：" + b);
        if (a == b) {
            room.setTime(0);// 房间内所有人已对抢庄做出选择，提前结束抢庄
            timer = 0;
            System.out.println("房间时间" + room.getTime());
        }
        return timer;
    }
    /**
     * @description :下注结束
     * 修改状态
     * @param room
     * @param map
     * @return: void
     * @date : 2019/10/10 9:25
     * @author : jj
     * @throws
     */
    public int xzjs(RoomBeanP room, Map<String, Object> map){
        List<UserBean> collect = room.getGame_userlist().stream().filter(user -> user.getPower_type() != 1).collect(Collectors.toList());
      /*  if ()
        for (UserBean user : collect) {

            user.setFirst(Integer.valueOf(String.valueOf(jsonData.get("first"))));
            user.setSecond(Integer.valueOf(String.valueOf(jsonData.get("second"))));
            user.setThird(Integer.valueOf(String.valueOf(jsonData.get("third"))));
            map.put("type", "SiRenGameInciDent");
            map.put("messages", gson.toJson(room));
        }*/
        /*下注结束，返回提示*/
        room.setState(13);
        map.put("type", TypeBean.SiRenGameInciDent);
        map.put("messages", gson.toJson(room));
        sendMessageAll(map, room);
        /*添加筛子时间*/
        room.setTime(5);
        return room.getTime();
    }
    /**
     * @description :判断筛子时间结束
     * @param room
     * @param timer
     * @return: int
     * @date : 2019/10/9 16:11
     * @author : jj
     * @throws
     */
    public int ksysz(RoomBeanP room, int timer){
        // 房间人数
        int a = 0;
        // 下注人数
        int b = 0;
        // 循环判断该抢庄人数
        for (int i = 0; i < room.getUser_positions().length; i++) {
            if (room.getUser_positions()[i] == -1) {
                continue;
            }
            UserBean u = room.getUserBean(room.getUser_positions()[i]);
            a++;
            if (2 == u.getIdentify()) {
                b++;
            }
        }
        System.out.println("在座a：" + a + ",选择b：" + b);
        if (a == b) {
            room.setTime(0);// 房间内所有人已对抢庄做出选择，提前结束抢庄
            timer = 0;
            System.out.println("房间时间" + room.getTime());
        }
        return timer;
    }
    /**
     * @description :开始发牌
     * @param room
     * @param map
     * @param timer
     * @return: int
     * @date : 2019/10/10 9:30
     * @author : jj
     * @throws
     */
    public int ksfp(RoomBeanP room, Map<String, Object> map,int timer){
        //开始发牌
        room.setState(5);
        if (4 < room.getGame_type()) {
            // 开始发牌2张
            room.dealTwo();
            List<UserBean> game_userlist = room.getGame_userlist();
            for (UserBean userBean : game_userlist) {
                //判断下注可用
                pkx.port(userBean);
                if (userBean.getBrands().size() >1) {
                    //设置牌型
                    pkx.card(userBean);
                } else {
                    continue;
                }

            }
            // 修改房间状态
            map.put("type", TypeBean.SiRenGameInciDent);
            map.put("messages", gson.toJson(room));
            sendMessageAll(map, room);
            room.setState(6);
        } else if (room.getGame_type()>2&&room.getGame_type()<5){
            // 开始发牌四张
            room.deal();
            room.getGame_userlist().forEach(userBean->{
                //判断下注可用
                pkx.port(userBean);
            });
            // 修改房间状态
            map.put("type", TypeBean.SiRenGameInciDent);
            map.put("messages", gson.toJson(room));
            sendMessageAll(map, room);
            room.setState(11);
            room.setTime(room.getTime01());
            timer=room.getTime();
        }

        return timer;
    }
    /**
     * @description :进行比牌
     * @param room
     * @param map
     * @return: void
     * @date : 2019/10/10 9:32
     * @author : jj
     * @throws
     */
    public void jxbp(RoomBeanP room, Map<String, Object> map){
        UserBean uz = room.getUserBean(room.getBanker());
        for (int i = 0; i < room.getUser_positions().length; i++) {
            if (room.getUser_positions()[i] == room.getBanker() || room.getUser_positions()[i] == -1) {
                continue;
            }
            UserBean ux = room.getUserBean(room.getUser_positions()[i]);
            if (ux.getReady_state() == 4) {
                continue;
            }
            pkx.contrast(room, uz, ux);

        }
        map.put("type", TypeBean.SiRenGameInciDent);
        map.put("messages", gson.toJson(room));
        sendMessageAll(map, room);
        //动漫时间
        room.setState(7);
    }
    /**
     * @description :动漫结束
     * @param room
     * @param map
     * @param timer
     * @return: int
     * @date : 2019/10/11 11:22
     * @author : jj
     * @throws
     */
    public int grzports(RoomBeanP room, Map<String, Object> map,int timer){
        // 房间人数
        int a = 0;
        int b = 0;// 抢庄人数
        // 循环判断该抢庄人数
        for (int i = 0; i < room.getUser_positions().length; i++) {
            if (room.getUser_positions()[i] == -1) {
                continue;
            }
            a++;
            UserBean u = room.getUserBean(room.getUser_positions()[i]);
            if (u.getPower_type() == 2) {
                b++;
            }
        }

        System.out.println("在座a：" + a + ",组牌：" + b);
        /*房间内所有人已对抢庄做出选择，提前结束抢庄*/
        if (b == a) {
            room.setTime(0);
            timer = 0;

        }
        return timer;
    }
    /**
    * @description :存档
    * @param room 
    * @param map
    * @date : 2019/10/21 9:31
    * @author : jj
    */
    public int archive(RoomBeanP room, Map<String, Object> map){
        for (int i = 0; i < room.getUser_positions().length; i++) {
            UserBean ux = room.getUserBean(room.getUser_positions()[i]);
            if (room.getUser_positions()[i]==-1){
                continue;
            }
            if (ux.getReady_state() == 4) {
                continue;
            }
            if (ux.getIdentify()!=1){
                map.put("type", TypeBean.SiRenGameInciDent);
                map.put("messages", gson.toJson(room));
                sendMessageTo(map, ux);
            }
            if (ux.getBanker() == 2) {
                ux.setBanker(1);
            }
        }
        // 循环所有用户，存入战绩信息
        userRecordService.addList(room);

         return 1;
             }
    //---------------------------------------------------------------------------------
    /**
     * @description :四人大小进行结算
     * @param room
     * @param map
     * @param timer
     * @return: int
     * @date : 2019/10/10 9:40
     * @author : jj
     * @throws
     */
    public int jxjs(RoomBeanP room, Map<String, Object> map,int timer){
        // 结算
        int scount = 0;
        int sr = 0;
        // 判断是否通杀
        for (int i = 0; i < room.getUser_positions().length; i++) {
            if (room.getUser_positions()[i] == room.getBanker()) {
                continue;
            }
            if (room.getUser_positions()[i]==-1){
                continue;
            }
            UserBean ux = room.getUserBean(room.getUser_positions()[i]);
            if (ux.getReady_state() == 4) {
                continue;
            }
            if (ux.getHu_state() != 0) {
                sr++;
            }
            if (ux.getHu_state() == 2) {
                scount++;
            }
        }
        if (scount == sr) {
            // 通杀加倍
            room.setHint(1);
        }
        //获取用户
        UserBean uz = room.getUserBean(room.getBanker());
        /*闲家输了*/
        List <UserBean> userList=new ArrayList<> ();
        room.getGame_userlist().forEach(user->{
            if (user.getBanker()!=2){
               if (user.getHu_state()==2) {
                   user.getPotList().forEach(mny -> {
                       /*闲家*/
                       user.setMoney(user.getMoney()-mny);
                       user.setZfen(user.getZfen()-mny);
                       user.setSyfen(user.getSyfen()-mny);
                       /*庄家*/
                       uz.setMoney(uz.getMoney()+mny);
                       uz.setZfen(uz.getZfen()+mny);
                       uz.setSyfen(uz.getSyfen()+mny);
                   });
                   User ur = userService.getById(user.getUserid());
                   ur.setMoney(user.getMoney());
                   userService.updateById(ur);
               }else {

                   userList.add(user);
               }
            }
        });
        /*庄家输了*/
        userList.forEach(userBean -> {
                userList.forEach(us -> {
                    pkx.contrast(room, userBean, us);
                        //谁赢谁位置靠前
                    if (us.getHu_state() == 1) {
                        int i = userList.indexOf(us);
                        int j = userList.indexOf(userBean);
                        Collections.swap(userList, i, j);
                    }
                });
        });
        /*扣除金币*/
        userList.forEach(use -> {
            UserBean u=room.getUserBean(use.getUserid());
            u.getPotList().forEach(mny -> {
                    if (uz.getMoney()-mny>0) {
                        uz.setMoney(uz.getMoney() - mny);
                        uz.setZfen(uz.getZfen()-mny);
                        uz.setSyfen(uz.getSyfen()-mny);
                        u.setMoney(u.getMoney() + mny);
                        u.setZfen(u.getZfen() + mny);
                        u.setSyfen(u.getSyfen() + mny);
                    }else {
                        u.setMoney(u.getMoney()+uz.getMoney());
                        uz.setMoney(0);
                    }
                });
                User ur = userService.getById(u.getUserid());
                ur.setMoney(u.getMoney());
                userService.updateById(ur);
        });
        User ur=userService.getById(uz.getUserid());
        ur.setMoney(uz.getMoney());
        userService.updateById(ur);
        /*进行动漫过场*/
        room.setState(8);
        room.setTime(6);
        timer=room.getTime();
        return  timer;
    }


    /**
     * 发送消息给所有人
     *
     * @throws IOException
     */
    public synchronized void sendMessageAll (Map < String, Object > returnMap, RoomBeanP rb){
        for (UserBean userb : rb.getGame_userlist()) {
            PK_WebSocket_P webSocket = Public_State_P.clients.get(String.valueOf(userb.getUserid()));
            if (webSocket != null && webSocket.getSession().isOpen() && userb.getExit_state() == 0) {
                // 不等于自己的则发送消息
                webSocket.sendMessageTo(returnMap, userb);
            } else {
                continue;
            }
        }
    }
    public synchronized void sendMessageTo (Map < String, Object > returnMap,UserBean user ){
        PK_WebSocket_P webSocket = Public_State_P.clients.get(String.valueOf(user.getUserid()));
        if (webSocket != null && webSocket.getSession().isOpen() && user.getExit_state() == 0) {
            // 不等于自己的则发送消息
            returnMap.put("userId",user.getUserid());
            webSocket.sendMessageTo(returnMap, user);
        }
    }

}
